#! /bin/sh
#
#mount and umount api

set -e

mount_part_simple()
{
	part_type=$1
	part_num=$2
	dir_name=$3

	#fsck.$part_type -y /dev/mmcblk2p$part_num
	mount -t $part_type -o errors=continue /dev/mmcblk2p$part_num /mnt/$dir_name
	if [ $? -eq 0 ];then
		echo "mount $dir_name done\n"
	else
		echo "mount $dir_name failed\n"
	fi
}

mount_part()
{
	part_type=$1
	part_num=$2
	dir_name=$3


	mount -t $part_type -o errors=continue /dev/mmcblk2p$part_num /mnt/$dir_name
	if [ $? -eq 0 ];then
		echo "mount $dir_name done\n"
	else
		echo "mount $dir_name failed\n"
	fi

}

mount_partitions(){
	dir_name=$1
	if [ "$dir_name" == "sd" ];then 
		mount_part ext4 7 sd
	fi
	if [ "$dir_name" == "userconfig" ];then 
	mount_part_simple ext4 3 userconfig
	fi
	if [ "$dir_name" == "log" ];then 
		mount_part_simple ext4 5 log
	fi
	if [ "$dir_name" == "ota" ];then 
		mount_part_simple vfat 6 ota
	fi
}

umount_partitions(){
	dir_name=$1

	umount /mnt/$dir_name
	if [ $? -eq 0 ];then
	echo "umount /mnt/$dir_name done\n"
	else
	echo "umount /mnt/$dir_name failed\n"
	fi
}

fuser_partitions(){
	dir_name=$1

	fuser -mk /mnt/$dir_name
}

format_partitions(){                                                                         
        dir_name=$1                                                                         

        if [ "$dir_name" == "sd" ];then                                                     
		echo y | mkfs.ext4 -m 0 /dev/mmcblk2p7
        fi                                                                                  
        if [ "$dir_name" == "userconfig" ];then                                             
		mkfs.ext4 /dev/mmcblk2p3
        fi                                                                                  
        if [ "$dir_name" == "log" ];then                                                    
                mkfs.ext4 /dev/mmcblk2p5
        fi                                                                                  
        if [ "$dir_name" == "ota" ];then
                mkfs.vfat /dev/mmcblk2p6                                                    
        fi                                                                          
} 


case "$1" in
	mount)
		mount_partitions $2
		;;
	umount)
		umount_partitions $2
		;;
	fuser)
		fuser_partitions $2
		;;
	format)
		format_partitions $2
		;;
esac

exit 0